//
//  MBSpaceUserViewController.m
//  mibaotu
//
//  Created by admin on 16/9/14.
//  Copyright © 2016年 pegnk. All rights reserved.
//

#import "MBSpaceUserViewController.h"
#import "MBSpacePerfectInformationViewController.h"
#import "MBSpaceInFormationViewController.h"
#import "MBSpaceAttentionsViewController.h"
#import "MBSpaceMyParentChildShowViewController.h"
#import "MBSpaceNewsViewController.h"
#import "MBSpceGradeViewController.h"
#import "MBSpaceMyCollectionViewController.h"
#import "MBRecordController.h"
#import "MBSpaceMusicClassViewController.h"

#import "MBSpaceUserHeaderView.h"

@interface MBSpaceUserViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceUserHeaderViewDelegate> {
    UIView                  *navView;
    UILabel                 *myTitleLb;
    UIButton                *sendQZShowBt;
    
    UITableView             *_tableView;
    MBSpaceUserHeaderView   *_tableHeaderView;
    
    NSString                *_gradeStr;  //人物等级
    BOOL                    isNewMessage; //是否有新消息，默认no 没有
}

@end

@implementation MBSpaceUserViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    if ([UserManager standerDefult].userModel) {
        [self loadData];
        [_tableView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _gradeStr = @"1";
    isNewMessage = NO;
    // Do any additional setup after loading the view.
    [self onCreateUI];
    [self setBackItem];
}

- (void)setBackItem
{
    navView = [[UIView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 44)];
    navView.backgroundColor = [UIColor clearColor];
    [_tableHeaderView addSubview:navView];
    
    UIImage *img = [UIImage imageNamed:@"fanhui"];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame = CGRectMake(10, (44-img.size.height)/2., 80, img.size.height);
    [back setImage:img forState:UIControlStateNormal];
    [back setImage:img forState:UIControlStateHighlighted];
    [back setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80-img.size.width)];
    [back addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:back];
    
    myTitleLb = [[UILabel alloc]initWithFrame:CGRectMake(0, 7, SCREEN_WIDTH, 30)];
    myTitleLb.text = @"个人主页";
    myTitleLb.textAlignment = NSTextAlignmentCenter;
    myTitleLb.textColor = [UIColor whiteColor];
    [navView addSubview:myTitleLb];
    
    sendQZShowBt = [UIButton buttonWithType:UIButtonTypeCustom];
    sendQZShowBt.frame = CGRectMake(SCREEN_WIDTH-85, myTitleLb.top, 80, 30);
    [sendQZShowBt setTitle:@"发布亲子秀" forState:UIControlStateNormal];
    [sendQZShowBt setTitle:@"发布亲子秀" forState:UIControlStateHighlighted];
    [sendQZShowBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendQZShowBt setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    sendQZShowBt.titleLabel.font = [UIFont systemFontOfSize:14.f];
    sendQZShowBt.backgroundColor = [UIColor clearColor];
    [sendQZShowBt addTarget:self action:@selector(onSendQZShowAction) forControlEvents:UIControlEventTouchUpInside];
    [navView addSubview:sendQZShowBt];
}

- (void)onCreateUI
{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.tableHeaderView = [self setUpTableHeaderView];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _tableView.tableHeaderView = [self setUpTableHeaderView];
    navView.frame = CGRectMake(0, 20, SCREEN_WIDTH, 44);
    myTitleLb.frame = CGRectMake(0, 7, SCREEN_WIDTH, 30);
    sendQZShowBt.frame = CGRectMake(SCREEN_WIDTH-85, myTitleLb.top, 80, 30);
    [_tableView reloadData];
}

- (MBSpaceUserHeaderView *)setUpTableHeaderView
{
    if (!_tableHeaderView) {
        _tableHeaderView = [[MBSpaceUserHeaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 550*PERCEN)];
        _tableHeaderView.delegate = self;
    }
    _tableHeaderView.orientation = self.orientation;
    return _tableHeaderView;
}

#pragma mark - 数据加载
- (void)loadData
{
    [_tableHeaderView setUpdataUI];
    
    UserModel *model = [UserManager standerDefult].userModel;
     [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_FANSNUM_URL_PATH,model.UserID] view:nil success:^(id json) {

        if ([json[@"ret_code"] integerValue]==0) {
            NSDictionary *dic = json[@"data"];
            if ([dic isKindOfClass:[NSDictionary class]]) {
                _tableHeaderView.dataDic = dic;
                [_tableView reloadData];
            }
        }
    } failure:^(NSError *error) {

    }];
    
    //人物等级
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_GETGRADE_URL_PATH,model.UserID] view:nil success:^(id json) {

        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] intValue] == 0) {
                NSDictionary *dic = [json objectForKey:@"data"];
                _gradeStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"UserGrade"]];
                [_tableView reloadData];
            }
        }
    } failure:^(NSError *error) {

    }];
    
    //是否有心消息
    [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:SPACE_NEWMESSAGE_URL_PATH,model.UserID] view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([json isKindOfClass:[NSDictionary class]]) {
            if ([json[@"ret_code"] intValue] == 0) {
                isNewMessage = YES;
            } else {
                isNewMessage = NO;
            }
            [_tableView reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Actions
- (void)onBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -发布亲子秀
- (void)onSendQZShowAction
{
    MBRecordController *putShow = [[MBRecordController alloc]init];
    [self.navigationController pushViewController:putShow animated:YES];
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    NSArray *arr = [_customFileArr lastObject];
    return (arr.count > 0 ? arr.count : 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"MBSpaceHomeCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        UIImageView *headImgView = [[UIImageView alloc]initWithFrame:CGRectMake((ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), 32.5*PERCEN, 35*PERCEN, 35*PERCEN)];
        headImgView.backgroundColor = [UIColor clearColor];
        headImgView.tag = 100;
        [cell.contentView addSubview:headImgView];
        
        UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake(headImgView.right+20*PERCEN, (100*PERCEN-30)/2., 60, 30)];
        titleLb.backgroundColor = [UIColor clearColor];
        titleLb.textAlignment = NSTextAlignmentLeft;
        titleLb.textColor = [UIColor blackColor];
        titleLb.font = [UIFont systemFontOfSize:14.f];
        titleLb.tag = 101;
        [cell.contentView addSubview:titleLb];
        
        UIImage *rightImg = [UIImage imageNamed:@"arrow"];
        UIImageView *rightView= [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-(ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN)-rightImg.size.width, (100*PERCEN-rightImg.size.height)/2., rightImg.size.width, rightImg.size.height)];
        rightView.backgroundColor = [UIColor clearColor];
        rightView.image = rightImg;
        rightView.tag = 102;
        [cell.contentView addSubview:rightView];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake((ISIPAD?440*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):0), 100*PERCEN-1, (ISIPAD?SCREEN_WIDTH-880*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):SCREEN_WIDTH), 1)];
        lineView.backgroundColor = [UIColorFromHex(0xcccccc)colorWithAlphaComponent:.35];
        lineView.tag = 103;
        [cell.contentView addSubview:lineView];
        
        //我的信息消息提示
        UIImage *tipImg = [UIImage imageNamed:@"yuandian"];
        UIImageView *tipImgView= [[UIImageView alloc]initWithFrame:CGRectMake(titleLb.right, titleLb.top+10*PERCEN, tipImg.size.width, tipImg.size.height)];
        tipImgView.backgroundColor = [UIColor clearColor];
        tipImgView.image = tipImg;
        tipImgView.tag = 104;
        tipImgView.hidden = YES;
        [cell.contentView addSubview:tipImgView];
        
        //我的等级
        UILabel *levelLb = [[UILabel alloc]initWithFrame:CGRectMake(titleLb.right+10*PERCEN, titleLb.top, 120, 30)];
        levelLb.backgroundColor = [UIColor clearColor];
        levelLb.textAlignment = NSTextAlignmentLeft;
        levelLb.textColor = TINK_COLOR;
        levelLb.font = [UIFont systemFontOfSize:14.f];
        levelLb.tag = 105;
        levelLb.hidden = YES;
        [cell.contentView addSubview:levelLb];
    }
    
    UIImageView *headImgView =  (UIImageView *)[cell viewWithTag:100];
    UILabel *titleLb =  (UILabel *)[cell viewWithTag:101];
    UIImageView *rightView =  (UIImageView *)[cell viewWithTag:102];
    UIView *lineView =  (UIView *)[cell viewWithTag:103];
    UIImageView *tipImgView =  (UIImageView *)[cell viewWithTag:104];
    UILabel *levelLb =  (UILabel *)[cell viewWithTag:105];
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
                headImgView.image = [UIImage imageNamed:@"xiaoxi_zy"];
                headImgView.frame = CGRectMake((ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), (100*PERCEN - 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width)/2., 35*PERCEN, 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width);
                titleLb.text = @"我的消息";
                tipImgView.hidden = !isNewMessage;
            }
                break;
            case 1:
            {
                headImgView.image = [UIImage imageNamed:@"dengji_zy"];
                headImgView.frame = CGRectMake((ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), (100*PERCEN - 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width)/2., 35*PERCEN, 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width);
                titleLb.text = @"我的等级";
                levelLb.hidden = NO;
                levelLb.text = [NSString stringWithFormat:@"Lv.%@",_gradeStr];
            }
                break;
            case 2:
            {
                headImgView.image = [UIImage imageNamed:@"shoucang_kj"];
                headImgView.frame = CGRectMake((ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), (100*PERCEN - 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width)/2., 35*PERCEN, 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width);
                titleLb.text = @"我的收藏";
                
                lineView.hidden = YES;
            }
                break;
                
            default:
                break;
        }
    }
    else if (indexPath.section == 1) {
        //自定义
        headImgView.image = [UIImage imageNamed:@"fenlei_zy"];
        headImgView.frame = CGRectMake((ISIPAD ? 460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.) : 25*PERCEN), (100*PERCEN - 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width)/2., 35*PERCEN, 35*PERCEN*headImgView.image.size.height/headImgView.image.size.width);
        
        NSArray *arr = [_customFileArr lastObject];
        if (arr.count > indexPath.row) {
            NSDictionary *fileDic = [arr objectAtIndex:indexPath.row];
            titleLb.text = [[fileDic objectForKey:@"CateName"]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
        else if (arr.count == 0) {
            titleLb.text = @"您还没有自建分类";
        }
        titleLb.width = 220;
//        lineView.hidden = YES;
        rightView.hidden = YES;
    }
    
    if (ISIPAD) {
        titleLb.left = headImgView.right + 20*PERCEN;
        lineView.frame = CGRectMake(440*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.), 100*PERCEN-1, SCREEN_WIDTH-880*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.), 1);
        UIImage *rightImg = [UIImage imageNamed:@"arrow"];
        rightView.frame= CGRectMake(SCREEN_WIDTH-(ISIPAD?440*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN)-rightImg.size.width, (100*PERCEN-rightImg.size.height)/2., rightImg.size.width, rightImg.size.height);
        UIImage *tipImg = [UIImage imageNamed:@"yuandian"];
        tipImgView.frame = CGRectMake(titleLb.right, titleLb.top+10*PERCEN, tipImg.size.width, tipImg.size.height);
        levelLb.frame = CGRectMake(titleLb.right+10*PERCEN, titleLb.top, 120, 30);
    } else {
        titleLb.left = headImgView.right + 20*PERCEN;
        lineView.frame = CGRectMake(0, 100*PERCEN-1, SCREEN_WIDTH, 1);
        UIImage *rightImg = [UIImage imageNamed:@"arrow"];
        rightView.frame= CGRectMake(SCREEN_WIDTH-25*PERCEN-rightImg.size.width, (100*PERCEN-rightImg.size.height)/2., rightImg.size.width, rightImg.size.height);
        UIImage *tipImg = [UIImage imageNamed:@"yuandian"];
        tipImgView.frame = CGRectMake(titleLb.right, titleLb.top+10*PERCEN, tipImg.size.width, tipImg.size.height);
        levelLb.frame = CGRectMake(titleLb.right+10*PERCEN, titleLb.top, 120, 30);

    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 20*PERCEN;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        bgView.backgroundColor = [UIColor clearColor];
        
        UILabel *titleLb = [[UILabel alloc]initWithFrame:CGRectMake((ISIPAD?460*PERCEN*(self.orientation==UIDeviceOrientationPortrait?1.0*SCREEN_WIDTH/SCREEN_HEIGHT:1.):25*PERCEN), 10, 200, 20)];
        titleLb.backgroundColor = [UIColor clearColor];
        titleLb.textAlignment = NSTextAlignmentLeft;
        titleLb.textColor = UIColorFromHex(0x333333);
        titleLb.font = [UIFont systemFontOfSize:13.f];
        NSArray *fileArr = [_customFileArr lastObject];
        titleLb.text = [NSString stringWithFormat:@"自建分类(%d)",(int)(fileArr.count > 0 ?fileArr.count:0)];
        [bgView addSubview:titleLb];
        
        return bgView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //我的消息
            MBSpaceNewsViewController *news = [[MBSpaceNewsViewController alloc]init];
            [self.navigationController pushViewController:news animated:YES];
        }
        else if (indexPath.row == 1) {
            MBSpceGradeViewController *grade = [[MBSpceGradeViewController alloc]init];
            [self.navigationController pushViewController:grade animated:YES];
        }
        else if (indexPath.row == 2) {
            MBSpaceMyCollectionViewController *collection = [[MBSpaceMyCollectionViewController alloc]init];
            collection.type = MBSpaceMyCollectionShowType_Collection;
            [self.navigationController pushViewController:collection animated:YES];
        }
    }
    else if (indexPath.section == 1) {
        NSArray *fileArr = [_customFileArr lastObject];
        if (fileArr.count > indexPath.row) {
            NSDictionary *fileDic = [fileArr objectAtIndex:indexPath.row];
            MBSpaceMusicClassViewController *music = [[MBSpaceMusicClassViewController alloc]init];
            music.type = MusicClassType_Custom;
            music.dataDic = fileDic;
            music.albumName = [[fileDic objectForKey:@"CateName"]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [self.navigationController pushViewController:music animated:YES];
        }

    }
}

//MARK:头像、描述、关注、粉丝、亲子秀
//头像
- (void)onSelectItemWithHeadImgForView:(MBSpaceUserHeaderView *)view
{
    MBSpacePerfectInformationViewController *information = [[MBSpacePerfectInformationViewController alloc]init];
    [self.navigationController pushViewController:information animated:YES];
}
//描述
- (void)onSelectItemWithDescribe:(NSString *)describe withView:(MBSpaceUserHeaderView *)view
{
    UserModel *model = [UserManager standerDefult].userModel;
    NSString *signature = model.Signature;
    if ([model.Signature isKindOfClass:[NSNull class]]) {
        signature = @"";
    }
    
    MBSpaceInFormationViewController *information = [[MBSpaceInFormationViewController alloc]init];
    information.isSign = YES;
    information.signTitle = signature;
    information.InformationBlock = ^(NSString *showName) {
        _tableHeaderView.describeString = showName;
    };
    [self.navigationController pushViewController:information animated:YES];
}
//关注
- (void)onSelectItemWithAttention:(NSString *)describe withView:(MBSpaceUserHeaderView *)view
{
    MBSpaceAttentionsViewController *attention = [[MBSpaceAttentionsViewController alloc]init];
    attention.type = MBSpaceAttentionType_MyAttention;
    [self.navigationController pushViewController:attention animated:YES];
}
//粉丝
- (void)onSelectItemWithFans:(NSString *)describe withView:(MBSpaceUserHeaderView *)view
{
    MBSpaceAttentionsViewController *attention = [[MBSpaceAttentionsViewController alloc]init];
    attention.type = MBSpaceAttentionType_Fans;
    [self.navigationController pushViewController:attention animated:YES];
}
//亲子秀
- (void)onSelectItemWithParentChildShow:(NSString *)describe withView:(MBSpaceUserHeaderView *)view
{
    MBSpaceMyParentChildShowViewController *show = [[MBSpaceMyParentChildShowViewController alloc]init];
    show.type = MBSpaceMyParentChildShowType_Remote;
    [self.navigationController pushViewController:show animated:YES];
}

@end
